<template>
  <div p-32rpx>
    <div>
      <div flex flex-col flex-a-c>
        <image w-392rpx h-296rpx src="@/static/pay.png"></image>
        <div>收银台</div>
        <div text-main-color font-bold my-20rpx text-62rpx>{{ unitPrice(cashierInfo.price, '￥') }}</div>
        <div flex flex-a-c my-20rpx><span mr-20rpx>剩余支付时间</span>
          <nut-config-provider :theme-vars="{
          countdownFontSize: '40rpx',
          countdownColor: colors.themeColor
        }">
            <nut-countdown :end-time="cancelCountDown"></nut-countdown>
          </nut-config-provider>
        </div>

      </div>
      <div mb-20rpx mt-100rpx text-30rpx>支付方式</div>
      <!-- 循环支付方式 -->
      <div v-for="(item, index) in payList" :key="index">
        <div>
          <div @click="awaitPay(item, index)">
            <div v-if="item == 'ALIPAY'" class="pay-item">
              <image w-64rpx h-64rpx src="@/static/alipay.png" />
              <span ml-20rpx>支付宝</span>
            </div>
            <!-- <div v-if="item == 'WECHAT_PARTNER'" class="pay-item">
              <image w-64rpx h-64rpx src="@/static/weichat.png" />

              <span ml-20rpx>微信</span>
            </div> -->
            <div v-if="item == 'WECHAT'" class="pay-item">
              <image w-64rpx h-64rpx src="@/static/weichat.png" />

              <span ml-20rpx>微信</span>
            </div>
            <div v-if="item == 'WALLET'" class="pay-item">
              <image w-64rpx h-64rpx src="@/static/wallet.png" />

              <span ml-20rpx>余额支付(当前余额：{{ unitPrice(cashierInfo.walletValue, '￥') }})</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <nut-toast ref="toastRef" />
    <nut-dialog title="设置支付密码" content="点击确定去设置支付密码" v-model:visible="setUpPassword" @ok="setupPassword" />
    <nut-popup position="bottom" round :custom-style="{ height: '300rpx' }" v-model:visible="paymentData.show">
      <div p-32rpx flex flex-a-c flex-col>
        <div text-28rpx mb-60rpx>请输入支付密码</div>
        <nut-code-input size="40" hairline font-size="24" dot space="20" :maxlength="6" focus mode="line"
          @finish="finishedPassword" v-model="paymentData.paymentPassword" />
      </div>
    </nut-popup>

  </div>
</template>

<script setup lang="ts">
import { checksetUpPassword, isCheckPassword } from '@/api/login';
import { getCashierData, initiatePay, payCallback } from '@/api/trade';
import { colors } from '@/constants/injection-key';
import { unitPrice } from '@/utils/filters';
import { onLoad } from '@dcloudio/uni-app';
import type { ToastInst } from 'nutui-uniapp';
import { Md5 } from 'ts-md5';
const toastRef = ref<ToastInst>() // toast
const setUpPassword = ref<boolean>(false)
const sn = ref<string>('')
const orderType = ref<string>('')
const paymentType = ref<string>('') // 支付方式
const paymentClient = ref<string>('') // 支付客户端
const cashierInfo = ref<any>('')
const payList = ref<any>([])
const routerVal = ref<any>('')
const cancelCountDown = ref<number>(0) //支付倒计时
const paymentData = ref({
  show: false, //余额支付输入密码模态框
  paymentPassword: "" // 支付密码
})

// 获取收银台详情
async function init() {
  const params = {
    sn: sn.value,
    orderType: orderType.value,
    clientType: paymentType.value
  }
  const res = await getCashierData(params)
  if (res.data.success) {
    cashierInfo.value = res.data.result
    cancelCountDown.value = res.data.result.autoCancel

    // #ifdef MP-WEIXIN
    payList.value = res.data.result.support.filter((item: any) => {
      return item != "ALIPAY";
    });
    // #endif


    if (routerVal.value.recharge_sn) {
      payList.value = res.data.result.support.filter((item: any) => {
        return item != "WALLET";
      })
    } else {
      payList.value = res.data.result.support;
    }


    // #ifdef H5
    //判断是否微信浏览器
    if (isWeiXin()) {
      payList.value = res.data.result.support.filter((item: any) => {
        return item != "ALIPAY";
      });
      // 充值的话仅保留微信支付
      if (orderType.value == "RECHARGE") {
        payList.value = res.data.result.support.filter((item: any) => {
          return item == "WECHAT";
        });
      }

    }
    // #endif
  }
}

function setupPassword() {
  uni.navigateTo({
    url: "/pages/mine/pin/pay",
  });
}

async function awaitPay(payment: any, index: number) {

  // 余额支付
  if (payment === 'WALLET') {
    // 校验是否设置了支付密码
    const res = await checksetUpPassword()
    if (res.data) {
      paymentData.value.show = true
    }
    else {
      setUpPassword.value = true
    }
  } else {
    pay(payment)
  }
}

async function finishedPassword() {
  const res = await isCheckPassword({
    password: Md5.hashStr(paymentData.value.paymentPassword)
  })
  if (res.data) {
    paymentData.value.show = false

    pay('WALLET')
  } else {
    uni.showToast({
      title: '支付密码输入错误',
      icon: "none"
    })
    paymentData.value.paymentPassword = ''
  }
}

async function pay(payment: string) {
  let params = {
    sn: sn.value,
    orderType: orderType.value,
    clientType: paymentType.value,
  };

  //支付方式 WECHAT/ALIPAY
  const paymentMethod = payment;
  // 客户端类型 APP/NATIVE/JSAPI/H5



  // #ifdef APP-PLUS
  envAppPay(paymentMethod, params)
  // #endif


  //#ifdef H5
  envH5Pay(paymentMethod, params)
  // #endif

  //#ifdef MP-WEIXIN
  envWechatPay(paymentMethod, params)
  // #endif
}

// 环境H5支付
async function envH5Pay(paymentMethod: string, params: any) {
  toastRef.value?.showToast['loading']('加载中', {
    cover: true,
    duration: 0
  })
  const response = await initiatePay(paymentMethod, paymentClient.value, params)
  if (response.data.success) {
    //如果非支付宝支付才需要进行判定，因为支付宝h5支付是直接输出的，没有返回所谓的消息状态
    if (paymentMethod !== "ALIPAY") {
      //如果支付异常
      if (!response.data.success) {
        uni.showToast({
          title: response.data.message,
          duration: 2000,
          icon: "none"
        });
        return;
      }
      if (paymentMethod === "ALIPAY") {
        document.write(response.data);
      } else if (paymentMethod === "WECHAT") {
        if (isWeiXin()) {
          //微信公众号支付
          WeixinJSBridge.invoke(
            "getBrandWCPayRequest",
            response.data.result,
            (res: any) => {
              if (res.err_msg == "get_brand_wcpay_request:ok") {
                // 使用以上方式判断前端返回,微信团队郑重提示：
                //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                uni.showToast({
                  icon: "none",
                  title: "支付成功!",
                });
                callback(paymentMethod)

              } else {
                uni.showModal({
                  content: "支付失败,如果您已支付，请勿反复支付",
                  showCancel: false,
                });
              }
            }
          );
          uni.hideLoading();
        } else {
          window.location.href = JSON.parse(response.data.result).h5_url;
          const searchParams = {
            ...params,
            price: cashierInfo.value,
          }
          const timer = setInterval(() => {
            payCallback(searchParams).then(res => {
              if (res.data.result) {
                clearTimeout(timer);
                uni.navigateTo({
                  url: "/pages/order/myOrder"
                })
              }
            })
          }, 3000)

          uni.hideLoading();
        }
      } else if (paymentMethod === "WALLET") {
        if (response.data.success) {
          if (response.data.result) {
            cashierInfo.value.price = response.data.result
          }
          callback(paymentMethod)
        }
      }
    }
  } else {
    toastRef.value?.hideToast();
  }
}

// 环境APP支付
async function envAppPay(paymentMethod: string, params: any) {
  toastRef.value?.showToast['loading']('加载中', {
    cover: true,
    duration: 0
  })
  const signXml = await initiatePay(paymentMethod, paymentClient.value, params)
  toastRef.value?.hideToast();
  if (signXml.data.success) {
    if (signXml.data.result.url) {
      let payForm = signXml.data.result;

      const methods: any = {
        "WECHAT_PARTNER": 'wxpay',
        "WECHAT": 'wxpay',
      }
      let paymentType = methods[paymentMethod] || 'alipay'
      // 零钱支付
      if (paymentMethod === "WALLET") {
        cashierInfo.value.price = payForm
        callback(paymentMethod)
      } else {
        // 微信/支付宝支付
        uni.requestPayment({
          provider: paymentType,
          orderInfo: payForm || '',
          success: (e) => {
            uni.showToast({
              icon: "none",
              title: "支付成功!",
            });
            callback(paymentMethod)
          },
          fail: (e) => {
            uni.showModal({
              content: "支付失败,如果您已支付，请勿反复支付",
              showCancel: false,
            });
          },
        });

      }

    }
  }
}

// 环境微信支付
async function envWechatPay(paymentMethod: string, params: any) {
  toastRef.value?.showToast['loading']('加载中', {
    cover: true,
    duration: 0
  })
  const res = await initiatePay(paymentMethod, paymentClient.value, params)
  toastRef.value?.hideToast();
  let response = res.data.result;
  //如果支付异常
  if (!res.data.success) {
    uni.showModal({
      content: res.data.message,
      showCancel: false,
    })
    return;
  }

  if (paymentMethod === "WECHAT" || paymentMethod === "WECHAT_PARTNER") {
    uni.requestPayment({
      provider: "wxpay",
      appid: response.appId,
      timeStamp: response.timeStamp,
      nonceStr: response.nonceStr,
      package: response.package,
      signType: response.signType,
      paySign: response.paySign,
      success: (e) => {
        uni.showToast({
          icon: "none",
          title: "支付成功!",
        });
        callback(paymentMethod)

      },
      fail: (e) => {
        console.log(e);
        uni.showModal({
          content: "支付失败,如果您已支付，请勿反复支付",
          showCancel: false,
        });
      },
    });
  } else {
    uni.showToast({
      icon: "none",
      title: "支付成功!",
    });
    callback(paymentMethod)

  }
}

/**
 * 支付成功后跳转
 */
function callback(paymentMethod: string) {
  uni.redirectTo({
    url: "/pages/mine/payment/success?paymentMethod=" +
      paymentMethod +
      "&payPrice=" +
      cashierInfo.value.price +
      "&orderType=" + orderType.value
  });
}

// 是否是微信内部浏览器
function isWeiXin() {
  var ua = window.navigator.userAgent.toLowerCase();
  if (!!ua.match(/MicroMessenger/i)) {
    return true;
  } else {
    return false;
  }
}

onMounted(() => {

})

onLoad((option: any) => {
  routerVal.value = option

  //初始化参数
  // #ifdef APP-PLUS
  paymentType.value = "APP";
  paymentClient.value = "APP";
  //#endif
  // #ifdef MP-WEIXIN
  paymentType.value = "WECHAT_MP";
  paymentClient.value = "MP";
  //#endif
  // #ifdef H5
  paymentType.value = "H5";

  //如果是微信浏览器，则使用公众号支付，否则使用h5，
  // 区别是：h5是通过浏览器外部调用微信app进行支付，而JSAPI则是 在微信浏览器内部，或者小程序 调用微信支付
  paymentClient.value = isWeiXin() ? "JSAPI" : "H5";
  //#endif

  if (routerVal.value.recharge_sn) {
    // 判断当前是否是充值
    sn.value = routerVal.value.recharge_sn;
    orderType.value = "RECHARGE";
  } else if (routerVal.value.trade_sn) {
    sn.value = routerVal.value.trade_sn;
    orderType.value = "TRADE";
  } else {
    sn.value = routerVal.value.order_sn;
    orderType.value = "ORDER";
  }

  init()
})

</script>

<style scoped>
:root,
page {
  background: #fff;
}
</style>

<style scoped lang="scss">
.pay-item {
  display: flex;
  align-items: center;
  padding: 40rpx 0;
  border-bottom: 2rpx solid #ededed;
}
</style>
